package com.wchen.project.zk.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @Desc:   同步方式更新节点数据内容
 *
 * @author: cww
 * @DateTime: 2020-01-18 15:41
 */

public class ZooKeeperSetDataSyncAPI  implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zk = null;

    public static void main(String[] args) throws Exception{
        String path = "/zk-book";
        zk = new ZooKeeper("home:2181", 5000, new ZooKeeperSetDataSyncAPI());
        connectedSemaphore.await();
        zk.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        zk.getData(path, true, null);
        // 如果对 Zk 数据节点的更新操作没有原子性要求，那么就可以使用 -1
        Stat stat = zk.setData(path, "456".getBytes(), -1);
        System.out.println("Czxid: " + stat.getCzxid() + ", Mzxid: " + stat.getMzxid() + ", Version: " + stat.getVersion());

        Stat stat2 = zk.setData(path, "456".getBytes(), -1);
        System.out.println("Czxid: " + stat2.getCzxid() + ", Mzxid: " + stat2.getMzxid() + ", Version: " + stat2.getVersion());
        // 本次操作将抛出 KeeperErrorCode = BadVersion for /zk-book 异常，因为用的是旧的版本号
        zk.setData(path, "456".getBytes(), stat.getVersion());
        Thread.sleep(5000);
    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.EventType.None == event.getType() && null == event.getPath()) {
            connectedSemaphore.countDown();
        }
    }
}
